<?php

/**
* Directions.class.php
*
* Google Direction API wraper
*
* @author     Blazej Zieba <b@zieba.info>
* @copyright  2007 konekto.com
* @version    CVS: $Id:$
*/

require_once("framework/config.php");
require_once("framework/UserErrorHandler.class.php");
require_once("framework/ExceptionHandler.class.php");
require_once("HTML/QuickForm.php");
require_once("HTTP/Request2.php");
require_once("Services/JSON.php");


// {{{ Directions 

class Directions 
{
    var $gdata;
    // {{{ Class operations 

    // {{{ Directions
    /**
    * C'tor
    */
    function Directions($origin,$destination,$lang)
    {
        if ( !isSet($origin) || !isSet($destination) || !isSet($lang) )
        {
            trigger_error("Directions::Directions() origin or destination not set", E_USER_ERROR); 
        }

        $options = &PEAR::getStaticProperty('CONFIG_INI','DIRECTIONS');
        $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

        $url = "http://maps.google.com/maps/api/directions/json?";
        $url.= "origin=".urlencode($origin)."&";
        $url.= "alternatives=false&"; 
        $url.= "destination=".urlencode($destination)."&";
        $url.= "mode=walking&";
        //$url.= "units=".$form->getElementValue('units')."&";
        $url.= "language=".$lang."&";
        $url.= "sensor=false";
        

        $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);

        list($host, $port) = split(':', $global['proxy']);
        $request->setConfig('proxy_host',$host);     
        $request->setConfig('proxy_port',$port);     

        $response = $request->send();
    
        if (200 == $response->getStatus()) {
            $json = new Services_JSON();
            $this->gdata = $json->decode($response->getBody());
        } else {
            trigger_error("Directions::Directions() Unexpected HTTP status (".$url."): " . $response->getStatus() . " " .$response->getReasonPhrase(), E_USER_ERROR); 
        }
            
    }
    // }}}

    // {{{ getEncPolyline
    /***
    * getData data received from google
    */
    function getEncPolyline()
    {
        $encPolyline = null;
        $encPolyline = $this->gdata->routes[0]->overview_polyline->points;
        return $encPolyline;
    }
    // }}}

    // {{{ getDistance
    /***
    * getData data received from google
    */
    function getDistance()
    {
        return $this->gdata->routes[0]->legs[0]->distance->text;
    }
    // }}}

    // {{{ getHtmlInstructions
    /***
    * getData data received from google
    */
    function getHtmlInstructions()
    {
        $route = array();

        foreach ( $this->gdata->routes[0]->legs as $leg ) 
        {
            foreach($leg->steps as $step )
            {
                $route[] = $step->html_instructions;
            }
        }

        return $route;
    }
    // }}}
    
}


